package com.zyf.user.config;

import com.zyf.user.pojo.MyUserDetail;
import com.zyf.user.pojo.User;
import com.zyf.user.service.impl.RoleServiceImpl;
import com.zyf.user.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class UserDetailServiceImpl implements UserDetailsService, Serializable {
    @Autowired
    UserServiceImpl userService;
    @Autowired
    RoleServiceImpl roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.selectByUserName(username);
        if (user == null) {
            return null;
        }
        List<String> list = userService.selectRoleByName(username);
        Set set = new HashSet();
        for (String items : list) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(items);
            set.add(grantedAuthority);
        }
        MyUserDetail myUserDetail = new MyUserDetail();
        myUserDetail.setUsername(username);
        //数据库没加密
        myUserDetail.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        myUserDetail.setAuthorities(set);
        return myUserDetail;
    }
}
